import { Injectable } from '@angular/core'
import { HttpClient } from '@angular/common/http'
import { Observable, throwError } from 'rxjs'
import { map, catchError } from 'rxjs/operators'

import { IMenu, IMenuOrdinal } from '@shared/interfaces/role'
import { COMB_URL } from 'app/utils/contraints'

@Injectable()
export class MenuService {
  constructor(
    private http: HttpClient,
  ) {}

  getMenus(): Observable<IMenu[]> {
    const compareFunc = (a: IMenu, b: IMenu): number => (a.ordinal - b.ordinal)
    const url = `${COMB_URL}/camel/menus`
    return this.http.get<IMenu[]>(url, {}).pipe(
      map(list => list.sort(compareFunc).map((item, idx) => {
        item.ordinal = idx + 1
        return item
      }))
    )
  }

  createMenu(menu: IMenu): Observable<boolean> {
    const url = `${COMB_URL}/camel/menu`
    return this.http
      .post<any>(url, menu, {
        observe: 'response',
      })
      .pipe(
        map(resp => {
          const { status } = resp
          if (status === 201) {
            return true
          }

          throwError(resp)
        }),
        catchError(error => {
          return throwError(error)
        }),
      )
  }

  resetAll(menus: IMenuOrdinal[]): Observable<IMenu[]> {
    const url = `${COMB_URL}/camel/menu/ordinal`
    return this.http
      .put<IMenu[]>(url, menus, {
        observe: 'response',
      })
      .pipe(
        map(resp => {
          const { status } = resp
          if (status === 200) {
            return resp.body
          }

          throwError(resp)
        }),
        catchError(error => {
          return throwError(error)
        }),
      )
  }
}
